package com.ckf.login_wx.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.sql.visitor.functions.Length;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckf.login_wx.entity.Bill;
import com.ckf.login_wx.entity.Material;
import com.ckf.login_wx.entity.Odd;
import com.ckf.login_wx.entity.Repertory;
import com.ckf.login_wx.entity.RepertoryNum;
import com.ckf.login_wx.entity.RepertoryXH;
import com.ckf.login_wx.entity.Sell;
import com.ckf.login_wx.entity.Xinsell;
import com.ckf.login_wx.servic.OddService;
import com.ckf.login_wx.servic.BillService;
import com.ckf.login_wx.servic.RepertoryNumService;
import com.ckf.login_wx.servic.RepertoryXHService;
import com.ckf.login_wx.servic.XinsellService;
import com.ckf.login_wx.servic.RepertoryService;
import com.ckf.login_wx.servic.SellService;
import com.ckf.login_wx.util.Getpo;
import com.ckf.login_wx.util.Idname;
import com.github.pagehelper.PageHelper;

@RestController
@RequestMapping("/Sp")
public class SpSellcontroller {

	@Autowired
    private XinsellService XinsellService;
	@Autowired
    private OddService OddService;
	@Autowired
    private BillService billService;
	@Autowired
    private RepertoryService repertoryService;
	@Autowired
    private RepertoryXHService repertoryXHService;
	@Autowired
    private RepertoryNumService repertoryNumService;
    @RequestMapping("/selexinsellsearch")
    public Object selexinsellsearch(HttpServletRequest request,String odd,String modele,String name,String name2,String time,String anq,String site){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
        HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
    	//构造器定义
    	QueryWrapper<Odd> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Xinsell> queryWrapperodd = new QueryWrapper<>();
    	//构造odd条件用于搜索odd
        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
        queryWrapper.eq("status", 1);
      //制单员和销售只能看自己的

        System.out.println("******************************"+quxian);
    	if(quxian.equals("11")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("saisie",truename);
    	}
    	if(quxian.equals("2")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("anq",truename)
            .like("name2", name2)
    		.like("site", site);
    	}else{
            queryWrapper.like("name2", name2)
    		.like("anq", anq)
    		.like("site", site);
    	}
    	//开始搜索odd
    	List<Odd> oddlist= OddService.list(queryWrapper);
        //定义存放odd部分搜索出来的cid
    	List<String> stu=new ArrayList<String>();
        for (int j = 0; j < oddlist.size(); j++) {
        	stu.add(oddlist.get(j).getCid());
		}
        //开始构造搜索xinsell的条件
        queryWrapperodd.like("modele", modele)
		.like("name", name)
		.like("odd", odd);
        //开始搜索xinsell
    	List<Xinsell> a= XinsellService.list(queryWrapperodd);
    	//定义存放xinsell的最终结果集
    	List<Xinsell> a2= new ArrayList<Xinsell>();
    	//开始筛选odd和xinsell的共同部分
		for (int j = 0; j < a.size(); j++) {
			for (String key : stu) {
				if(a.get(j).getCid().equals(key))a2.add(a.get(j));
			}
		}
    	Map<String, Object> map = new HashMap<>();
    	//统计部分
    	double total=0;int quantite=0;
    	for (int t = 0; t < a2.size(); t++) {
			total+=a2.get(t).getTotal();
			quantite+=a2.get(t).getQuantite();
		}
    	map.put("code",0);
        map.put("count",a2.size());
        map.put("msg"," ");
        map.put("total",total);
        map.put("quantite",quantite);
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",a2);
        return map;
    }
    @RequestMapping("/seleoddsearch")
    public Object seleoddsearch(HttpServletRequest request,String odd,String modele,String name,String name2,String time,String anq,String status,String site){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	//构造器定义
    	QueryWrapper<Odd> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Xinsell> queryWrapperodd = new QueryWrapper<>();
        //定义存放Xinsell部分搜索出来的cid
    	List<String> stu=new ArrayList<String>();
    	//开始构造条件准备搜索Xinsell
        queryWrapperodd.like("modele", modele)
		.like("name", name)
		.like("odd", odd);
        //搜索Xinsell
    	List<Xinsell> a= XinsellService.list(queryWrapperodd);
    	//存放cid到stu
    	for (int j = 0; j < a.size(); j++) {
    		if(!stu.contains(a.get(j).getCid()))
        	stu.add(a.get(j).getCid());
		}
    	//构造odd条件
        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
        if(!status.equals("")){
            queryWrapper.eq("status", status);
        }
      //制单员和销售只能看自己的
        HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
    	if(quxian.equals("11")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("saisie",truename);
    	}
    	if(quxian.equals("2")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("anq",truename)
            .like("name2", name2)
    		.like("site", site);
    	}else{
            queryWrapper.like("name2", name2)
    		.like("anq", anq)
    		.like("site", site);
    	}
    	//搜索odd
    	queryWrapper.orderByDesc("odd");
    	List<Odd> oddlist= OddService.list(queryWrapper);
        //定义存放最终的odd结果集（放到map）
    	List<Odd> a2= new ArrayList<Odd>();
    	//开始筛选odd和xinsell的共同部分
		for (int j = 0; j < oddlist.size(); j++) {
			for (String key : stu) {
				if(oddlist.get(j).getCid().equals(key))
					a2.add(oddlist.get(j));
			}
		}
		//统计部分
		Double debt=0.00;
		for (int j = 0; j < a2.size(); j++) {
			debt+=a2.get(j).getDebt();
		}
    	Map<String, Object> map = new HashMap<>();
    	map.put("debt",debt);
    	map.put("code",0);
        map.put("count",a2.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",a2);
        return map;
    }
    @GetMapping("/oddone")
    public Object oddone(String odd){
        return OddService.list((QueryWrapper<Odd>)Getpo.one("odd", odd)).get(0);
    }
    @GetMapping("/xinsellone")
    public Object xinsellone(String odd){
    	
        return XinsellService.list((QueryWrapper<Xinsell>)Getpo.one("odd", odd));
    }
    //layui窗口专用
    @GetMapping("/xinsellseleone")
    public Object xinsellseleone(String odd){
    	List<Xinsell> a=XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", odd));
        Map<String, Object> map = new HashMap<>();
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
        map.put("data",a);
        return map;
    }
    @RequestMapping("/selexinsell")
    public Object selexinsell(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	
    	HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        //用于获取总记录数
    	List<Xinsell> a= XinsellService.list(new QueryWrapper<Xinsell>().eq("status", 1));
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",XinsellService.list(new QueryWrapper<Xinsell>().eq("status", 1)));
        map.put("count",a.size());
    	//统计部分
    	double total=0;int quantite=0;
    	for (int t = 0; t < a.size(); t++) {
			total+=a.get(t).getTotal();
			quantite+=a.get(t).getQuantite();
		}
        map.put("total",total);
        map.put("quantite",quantite);
        if(quxian.equals("11")||quxian.equals("2")){
        	//开始搜索odd
        	List<Odd> oddlist= OddService.list();
	    	if(quxian.equals("11")){
	    		System.out.println("进入角色："+truename);
	    		oddlist= OddService.list(new QueryWrapper<Odd>().like("saisie", truename));
	    	}
	    	if(quxian.equals("2")){
	    		System.out.println("进入角色："+truename);
	    		oddlist= OddService.list(new QueryWrapper<Odd>().like("anq", truename));
	    	}
            //定义存放odd部分搜索出来的cid
        	List<String> stu=new ArrayList<String>();
            for (int j = 0; j < oddlist.size(); j++) {
            	stu.add(oddlist.get(j).getCid());
    		}
	    	//定义存放xinsell的最终结果集
	    	List<Xinsell> a2= new ArrayList<Xinsell>();
	    	//开始筛选odd和xinsell的共同部分
			for (int j = 0; j < a.size(); j++) {
				for (String key : stu) {
					if(a.get(j).getCid().equals(key))a2.add(a.get(j));
				}
			}
        	//if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",a2);
            map.put("count",a2.size());
        	//统计部分
        	for (int t = 0; t < a.size(); t++) {
    			total+=a.get(t).getTotal();
    			quantite+=a.get(t).getQuantite();
    		}
            map.put("total",total);
            map.put("quantite",quantite);
        }
    	map.put("code",0);
        map.put("msg"," ");
    return map;
    }
    @GetMapping("/delexinsell")
    public String delexinsell(int id,String cid){
		List<Xinsell> sellre =XinsellService.list(new QueryWrapper<Xinsell>().eq("id", id));
    	if(XinsellService.removeById(id)){
    		
    		removeRepertoryinfo(sellre);
			
    		
    		Odd odd=OddService.list(new QueryWrapper<Odd>().eq("cid", sellre.get(0).getCid())).get(0);
    		if(XinsellService.list(new QueryWrapper<Xinsell>().eq("cid", sellre.get(0).getCid())).size()==0){
    			OddService.removeById(odd.getId());
    			System.out.println("删除");
    		}
    		odd.setCount(odd.getCount()-1);//订单货物减一
    		OddService.updateById(odd);
    		return "成功！";
    	}
    	else
    		return "失败！";
    }
	@RequestMapping("/deleodd")
    public String deleodd(int id,String cid){
    	System.out.println(id+"******************"+cid);
    	List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", OddService.getById(id).getOdd()+""));
		List<Xinsell> xinsell=XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", OddService.getById(id).getOdd()+""));
		if(OddService.removeById(id)){
    		for (int i = 0; i < xinsell.size(); i++) {
    			XinsellService.removeById(xinsell.get(i).getId());//删除所属所有货物
			}
    		removeRepertoryinfo(xinsell);
    		

    		for (int i = 0; i < billlist.size(); i++) {
    			billService.removeById(billlist.get(i).getId());
			}
    		
    		return "删除成功！";
    	}
    	else
    		return "删除失败！";
    }
	//货单管理--订单信息
    @RequestMapping("/seleodd")
    public Object seleodd(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list(new QueryWrapper<Odd>().eq("status", 1).orderByDesc("odd"));
    	
    	
//    	Map<String, Odd> mapnetity = new HashMap<>();
//    	for (int m = 0; m < a.size(); m++) {
//			mapnetity.put(a.get(m).getCid(), a.get(m));
//		}
//    	List<Xinsell> a2= XinsellService.list();
//    	List<Sell> a3=new ArrayList<Sell>();
//    	for (int j = 0; j < a2.size(); j++) {
//			Sell sellentity =new Sell();
//			sellentity.setModele(a2.get(j).getModele());
//			sellentity.setName(a2.get(j).getName());
//			sellentity.setMoney(new Double(a2.get(j).getMoney()).intValue());
//			sellentity.setTotal(new Double(a2.get(j).getTotal()).intValue());
//			sellentity.setUnite(a2.get(j).getUnite());
//			
//			Odd o=mapnetity.get(a2.get(j).getCid());
//
//			sellentity.setOdd(o.getOdd());
//			sellentity.setCid(o.getCid());
//			sellentity.setName2(o.getName2());
//			sellentity.setPhone(o.getPhone());
//			sellentity.setSaisie(o.getSaisie());
//			sellentity.setTime(o.getTime());
//			sellentity.setTime2(o.getTime2());
//			sellentity.setTupian(o.getTupian());
//			sellentity.setSite(o.getSite());
//			sellentity.setAnq(o.getAnq());
//			a3.add(sellentity);
//		}
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",OddService.list(new QueryWrapper<Odd>().eq("status", 1).orderByDesc("odd")));
        map.put("count",a.size());
        //统计部分
      	Double debt=0.00;
      	for (int j = 0; j < a.size(); j++) {
      		debt+=a.get(j).getDebt();
      	}
        map.put("debt",debt);
        
    	HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";

    	if(quxian.equals("11")){
    		debt=0.00;
    		System.out.println("进入角色："+truename);

        	a= OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).orderByDesc("odd"));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename)));
            map.put("count",a.size());//统计部分
          	for (int j = 0; j < a.size(); j++) {
          		debt+=a.get(j).getDebt();
          	}
            map.put("debt",debt);
    	}
    	if(quxian.equals("2")){
    		debt=0.00;
    		System.out.println("进入角色："+truename);

        	a= OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).orderByDesc("odd"));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).orderByDesc("odd")));
            map.put("count",a.size());//统计部分
          	for (int j = 0; j < a.size(); j++) {
          		debt+=a.get(j).getDebt();
          	}
            map.put("debt",debt);
    	}
    	map.put("code",0);
        map.put("msg"," ");
    return map;
    }
  //欠款统计
    @RequestMapping("/seleoddtj")
    public Object seleoddtj(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list(new QueryWrapper<Odd>().eq("status", 1).ne("debt", 0));
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",OddService.list(new QueryWrapper<Odd>().eq("status", 1).ne("debt", 0)));
        map.put("count",a.size());
        //统计部分
      	Double debt=0.00;
      	for (int j = 0; j < a.size(); j++) {
      		debt+=a.get(j).getDebt();
      	}
        map.put("debt",debt);
        
    	HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";

    	if(quxian.equals("11")){
    		debt=0.00;
    		System.out.println("进入角色："+truename);

        	a= OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).ne("debt", 0));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).ne("debt", 0)));
            map.put("count",a.size());//统计部分
          	for (int j = 0; j < a.size(); j++) {
          		debt+=a.get(j).getDebt();
          	}
            map.put("debt",debt);
    	}
    	if(quxian.equals("2")){
    		debt=0.00;
    		System.out.println("进入角色："+truename);

        	a= OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).ne("debt", 0));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("anq", truename).ne("debt", 0)));
            map.put("count",a.size());//统计部分
          	for (int j = 0; j < a.size(); j++) {
          		debt+=a.get(j).getDebt();
          	}
            map.put("debt",debt);
    	}
    	map.put("code",0);
        map.put("msg"," ");
    return map;
    }
	@RequestMapping("/delexinsellall")
    public Object delexinsellall(String[] id){
    	
    	for (int i = 0; i < id.length; i++) {
    		try {
    			if(id[i].equals(""))continue;
    	    	int idint = Integer.parseInt(id[i]+"");
    	    	delexinsell(idint,"");
    	    	//XinsellService.removeById(idint);
			} catch (Exception e) {
				return "异常";
			}
		}
		return "删除成功";
    }
	@RequestMapping("/deleoddall")
    public Object deleoddall(String[] id){
    	
    	for (int n = 0; n < id.length; n++) {
    		try {
    			if(id[n].equals(""))continue;
    	    	int idint = Integer.parseInt(id[n]+"");
    	    	//OddService.removeById(idint);
    	    	List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", OddService.getById(idint).getOdd()+""));
    	    	List<Xinsell> xinsell=XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", OddService.getById(idint).getOdd()+""));
	    		if(OddService.removeById(idint)){
    	    		for (int i = 0; i < xinsell.size(); i++) {
    	    			XinsellService.removeById(xinsell.get(i).getId());//删除所属所有货物
    				}
    	    		removeRepertoryinfo(xinsell);
    	    		

    	    		for (int i = 0; i < billlist.size(); i++) {
    	    			billService.removeById(billlist.get(i).getId());
    				}
    	    	}
			} catch (Exception e) {
				return "异常";
			}
		}
		return "删除成功";
    }
	public void xinsellremove(String odd,int id) {
		if(odd.equals("null")){
	    	XinsellService.removeById(id);
		}else{
			
		}
	}
	//xinsell移除后，型号数量返还
	public void removeRepertoryinfo(List<Xinsell> sellre) {
		Map<String, Integer> mapre = new HashMap<>();
		//统计到mapre
		for (int i = 0; i < sellre.size(); i++) {
			if(!mapre.containsKey(sellre.get(i).getModele())){
				mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite());
			}else{
				int numre=mapre.get(sellre.get(i).getModele());
				mapre.remove(sellre.get(i).getModele());
				mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite()+numre);
			}
		}
		for (String s : mapre.keySet()) {
			if(repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).size()==0){
				RepertoryXH RepertoryXH=repertoryXHService.list(new QueryWrapper<RepertoryXH>().eq("modele", s)).get(0);
				RepertoryNum RepertoryNum =new RepertoryNum();
				RepertoryNum.setModele(RepertoryXH.getModele());
				RepertoryNum.setWall(RepertoryXH.getWall());
				RepertoryNum.setWeight(RepertoryXH.getWeight());
				RepertoryNum.setNum(mapre.get(s));
				RepertoryNum.setQuantite(mapre.get(s));
				repertoryNumService.save(RepertoryNum);
				
				Repertory Repertory=new Repertory();
				Repertory.setModele(RepertoryXH.getModele());
				Repertory.setWall(RepertoryXH.getWall());
				Repertory.setWeight(RepertoryXH.getWeight());
				Repertory.setNum(mapre.get(s));
				Repertory.setQuantite(mapre.get(s));
//				SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				String time = sdFormatter.format(new Date());
				Repertory.setTime(new Date());
				Repertory.setSaisie("程序生成:货单删除废弃时返还的货物");
				repertoryService.save(Repertory);
			}else{
				RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
				RepertoryNum.setNum(RepertoryNum.getNum()+mapre.get(s));
				repertoryNumService.updateById(RepertoryNum);
			}
		}
	}
	@RequestMapping("/ses")
    public String addxinsell(String[] b,Integer odd,String name2,String phone,String anq,String time,String time2,String site,String saisie,String tupian,String total,String moneytotal,String faf) throws ParseException{
		if(Integer.parseInt(moneytotal)>Integer.parseInt(total)){
			return "实收货款大于应收货款！";
		}
		//再次检查库存
		Map<String, Integer> maptotal = new HashMap<>();
		for (int n = 0; n < b.length; n++) {
			if(b[1+(n*6)].equals("运费"))continue;
			if(b[1+(n*6)].equals("")||b[1+(n*6)]==null)break;
			if(!maptotal.containsKey(b[1+(n*6)])){
				maptotal.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)]));
			}
			else{
				int z=maptotal.get(b[1+(n*6)]);
				maptotal.remove(b[1+(n*6)]);
				maptotal.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)])+z);//相同货物数量相加
			}
		}
		for (String string : maptotal.keySet()) {
			if(maptotal.get(string)>repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", string)).get(0).getNum()){
				return "库存型号不足:"+string;
			}
		}
		//修改是直接删掉再添加
		if(faf.equals("up")){
			//存型号和数量
			Map<String, Integer> mapre = new HashMap<>();
			List<Xinsell> sellre =XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", odd));
			if(!XinsellService.remove(new QueryWrapper<Xinsell>().eq("odd", odd))||!OddService.remove(new QueryWrapper<Odd>().eq("odd", odd)))return "修改失败";
			//统计到mapre
			for (int i = 0; i < sellre.size(); i++) {
				if(!mapre.containsKey(sellre.get(i).getModele())){
					mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite());
				}else{
					int numre=mapre.get(sellre.get(i).getModele());
					mapre.remove(sellre.get(i).getModele());
					mapre.put(sellre.get(i).getModele(), sellre.get(i).getQuantite()+numre);//相同货物数量相加
				}
			}
			for (String s : mapre.keySet()) {
				if(s.equals("运费"))continue;
				RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
				RepertoryNum.setNum(RepertoryNum.getNum()+mapre.get(s));
					repertoryNumService.updateById(RepertoryNum);
			}
		}
		if(!seleoddbycid(odd))return "单号已存在！";
		String uuid=""+UUID.randomUUID();
		uuid=uuid.substring(0,8);
		int count=0,sum=0;double total2=0;
		boolean f=false;
		//存型号和数量
		Map<String, Integer> map = new HashMap<>();
		Xinsell sell=new Xinsell();
		for (int n = 0; n < b.length; n++) {
			sell.setName(b[0+(n*6)]);
			sell.setModele(b[1+(n*6)]);
			sell.setUnite(b[3+(n*6)]);
			System.out.println(sell.returnstu());
			if(sell.returnstu()==""||sell.returnstu().length()==0)break;
			count++;
			sell.setQuantite(Integer.parseInt(b[2+(n*6)]));
			sell.setMoney(Double.parseDouble(b[4+(n*6)]));
			//sum+=Integer.parseInt(b[4+(n*6)]);
			sell.setOdd(odd);
			sell.setCid(uuid);
			sell.setTotal(Double.parseDouble(b[5+(n*6)]));
			sell.setStatus(1);
			f=XinsellService.save(sell);
			total2+=sell.getTotal();
			int ii=0;
			if(map.containsKey(b[1+(n*6)])){
				ii=map.get(b[1+(n*6)]);
				map.remove(b[1+(n*6)]);
				map.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)])+ii);
			}else
			map.put(b[1+(n*6)], Integer.parseInt(b[2+(n*6)]));
		}
		if(!f)return "失败";
		//库存统计数量返还
		for (String s : map.keySet()) {
			if(s.equals("运费"))continue;
				RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
				RepertoryNum.setNum(RepertoryNum.getNum()-map.get(s));
				repertoryNumService.updateById(RepertoryNum);
		}
		
		Odd oddEntity =new Odd();
		oddEntity.setCid(uuid);
		oddEntity.setOdd(odd);
		oddEntity.setCount(count);
		oddEntity.setName2(name2);
		oddEntity.setPhone(phone);
		oddEntity.setSaisie(saisie);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        oddEntity.setTime(simpleDateFormat.parse(time));
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        oddEntity.setTime2(simpleDateFormat2.parse(time2));
		oddEntity.setTupian(tupian);
		oddEntity.setTotal(total2);
		oddEntity.setDebt(total2-Double.parseDouble(moneytotal));
		oddEntity.setSite(site);
		oddEntity.setAnq(anq);
		oddEntity.setMoneytotal(Double.parseDouble(moneytotal));
		oddEntity.setStatus(1);
		oddEntity.setPrintstatus(0);
		//oddEntity.setTotal(sum);
		if(faf.equals("add")&&Double.parseDouble(moneytotal)!=0.00){
			Bill bill=new Bill();
	        bill.setMoney(Double.parseDouble(moneytotal));
	        bill.setOdd(odd+"");
	        bill.setTotal(total2);
	        bill.setDebt(total2);
	        bill.setSource("货款");
	        bill.setTime(simpleDateFormat.parse(time));
	        bill.setRemark("程序制单时实收金额记录");
	        bill.setSaisie(saisie);
	        bill.setAnq(anq);
	        bill.setPhone(phone);
	        bill.setName(name2);
	        bill.setStatus(1);
			billService.save(bill);
		}
		if(OddService.save(oddEntity)){
			return "成功";
		}else
		return "失败";
    }
	@RequestMapping("/seleoddbycid")
    public boolean seleoddbycid(int odd){
		if(OddService.list((QueryWrapper<Odd>)Getpo.one("odd", odd)).size()==0){
			return true;
		}else
		return false;
	}
	//查询逾期
	//**********************在sp外
//	@RequestMapping("/seleoddalltime")
//    public Map<String, String> seleoddalltime(){
//		List<Odd> odd=OddService.list();
//		Date now = new Date(); 
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
//
//
//		String hehe = dateFormat.format( now ); 
//		System.out.println(hehe+"******************"); 
//		//定义一个map存放时间和单号
//		Map<String, String> map = new HashMap<>();
//		for (int i = 0; i < odd.size(); i++) {
//			
//			map.put(odd.get(i).getOdd(), odd.get(i).getTime2());
//		}
//		return map;
//	}
	
	@RequestMapping("/xinselltotalInfo")
    public Object xinselltotalInfo(HttpServletRequest request,String odd,String modele,String name,String name2,String time,String anq,String site){
    	HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        //构造器定义
    	QueryWrapper<Odd> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Xinsell> queryWrapperodd = new QueryWrapper<>();
    	//构造odd条件用于搜索odd
        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
        queryWrapper.eq("status", 1);
      //制单员和销售只能看自己的

        System.out.println("******************************"+quxian);
    	if(quxian.equals("11")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("saisie",truename);
    	}
    	if(quxian.equals("2")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("anq",truename)
            .like("name2", name2)
    		.like("site", site);
    	}else{
            queryWrapper.like("name2", name2)
    		.like("anq", anq)
    		.like("site", site);
    	}
    	//开始搜索odd
    	List<Odd> oddlist= OddService.list(queryWrapper);
        //定义存放odd部分搜索出来的cid
    	List<String> stu=new ArrayList<String>();
        for (int j = 0; j < oddlist.size(); j++) {
        	stu.add(oddlist.get(j).getCid());
		}
        //开始构造搜索xinsell的条件
        queryWrapperodd.like("modele", modele)
		.like("name", name)
		.like("odd", odd);
        //开始搜索xinsell
    	List<Xinsell> a= XinsellService.list(queryWrapperodd);
    	//定义存放xinsell的最终结果集
    	List<Xinsell> xinsell= new ArrayList<Xinsell>();
    	//开始筛选odd和xinsell的共同部分
		for (int j = 0; j < a.size(); j++) {
			for (String key : stu) {
				if(a.get(j).getCid().equals(key))xinsell.add(a.get(j));
			}
		}
		
    	double total=0;int quantite=0;
    	for (int i = 0; i < xinsell.size(); i++) {
			total+=xinsell.get(i).getTotal();
			quantite+=xinsell.get(i).getQuantite();
			
		}
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("quantite",quantite);  
        return map;
    }
    @RequestMapping("/xinselltotal")
    public Object xinselltotal(HttpServletRequest request){
    	double total=0;int quantite=0;
    	
    	HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        List<Odd> Odd =OddService.list(new QueryWrapper<Odd>().eq("status", 1));
	    	if(quxian.equals("2")){
	    		Odd= OddService.list(new QueryWrapper<Odd>().eq("status", 1).eq("saisie", truename).or().eq("anq", truename));
	    	}
	    //定义存放odd部分搜索出来的cid
	    List<String> stu=new ArrayList<String>();
	    for (int j = 0; j < Odd.size(); j++) {
	        stu.add(Odd.get(j).getCid());
		}
    	List<Xinsell> a= XinsellService.list();
	    //定义存放xinsell的最终结果集
    	List<Xinsell> xinsell= new ArrayList<Xinsell>();
    	//开始筛选odd和xinsell的共同部分
		for (int j = 0; j < a.size(); j++) {
			for (String key : stu) {
				if(a.get(j).getCid().equals(key))xinsell.add(a.get(j));
			}
		}
    	//List<Xinsell> xinsell=XinsellService.list();
    	for (int i = 0; i < xinsell.size(); i++) {
			total+=xinsell.get(i).getTotal();
			quantite+=xinsell.get(i).getQuantite();
		}
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("quantite",quantite);
        return map;
    }
    //查询所有订单号
    @RequestMapping("/seleallodd")
    public Object seleallodd(HttpServletRequest request){
    	
    	HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        List<Odd> oddlist =OddService.list(new QueryWrapper<Odd>().eq("status", 1));
    	//制单员和销售只能看自己的
    	if(quxian.equals("2")){
    		oddlist= OddService.list(new QueryWrapper<Odd>().like("anq", truename).eq("status", 1));
    	}
    	List<String> s =new ArrayList<String>();
    	List<String> shopperinfo =new ArrayList<String>();
    	//Map<String, String> shopperinfo = new HashMap<>();
    	for(int i=0;i<oddlist.size();i++){
    		if(!s.contains(oddlist.get(i).getOdd())){
        		s.add(oddlist.get(i).getOdd()+"");
    			shopperinfo.add(oddlist.get(i).getOdd()+"("+oddlist.get(i).getName2()+":"+oddlist.get(i).getPhone()+")");
    		}
    	}
    	Map<String, Object> map = new HashMap<>();
        map.put("count",s.size());
        map.put("data",s);
        map.put("shopperinfo",shopperinfo);
        return map;
    }
    //货单启用和废弃
    @RequestMapping("/checkstatus")
    public Object checkStatus(String odd,Integer status){
        Odd oddentity=OddService.list(new QueryWrapper<Odd>().eq("odd", odd)).get(0);
        List<Xinsell> xinsell=XinsellService.list(new QueryWrapper<Xinsell>().eq("odd", oddentity.getOdd()));
        
        if(status==0){//返还增加
    		removeRepertoryinfo(xinsell);
    		List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", odd));
    		for (int i = 0; i < billlist.size(); i++) {
    			Bill billpo=billlist.get(i);
    			billpo.setStatus(0);
    			billService.updateById(billpo);
			}
        }
        if(status==1){//减少
        	Map<String, Integer> mapre = new HashMap<>();
    		//统计到mapre
    		for (int i = 0; i < xinsell.size(); i++) {
    			if(!mapre.containsKey(xinsell.get(i).getModele())){
    				mapre.put(xinsell.get(i).getModele(), xinsell.get(i).getQuantite());
    			}else{
    				int numre=mapre.get(xinsell.get(i).getModele());
    				mapre.remove(xinsell.get(i).getModele());
    				mapre.put(xinsell.get(i).getModele(), xinsell.get(i).getQuantite()+numre);
    			}
    		}
    		for (String s : mapre.keySet()) {
    			RepertoryNum RepertoryNum = repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", s)).get(0);
    			RepertoryNum.setNum(RepertoryNum.getNum()-mapre.get(s));
    			if(RepertoryNum.getNum()<0){
    				return "库存不足无法启用："+RepertoryNum.getModele();
    			}
    			repertoryNumService.updateById(RepertoryNum);
    		}
    		List<Bill> billlist=billService.list(new QueryWrapper<Bill>().eq("odd", odd));
    		for (int i = 0; i < billlist.size(); i++) {
    			Bill billpo=billlist.get(i);
    			billpo.setStatus(1);
    			billService.updateById(billpo);
			}
        }
        
        
        
        
        oddentity.setStatus(status);
        OddService.updateById(oddentity);
        for (int i = 0; i < xinsell.size(); i++) {
        	Xinsell xinsellentity=xinsell.get(i);
        	xinsellentity.setStatus(status);
        	XinsellService.updateById(xinsellentity);
		}
        
        return "";
    }
    @RequestMapping("/seleoddall")
    public Object seleoddall(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
		HttpSession session= request.getSession();
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list(new QueryWrapper<Odd>().orderByDesc("odd"));
    	if(quxian.equals("2")){
    		a=OddService.list(new QueryWrapper<Odd>().eq("anq", truename).orderByDesc("odd"));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("anq", truename).orderByDesc("odd")));
            map.put("count",a.size());
        	map.put("code",0);
            map.put("msg"," ");
        return map;
    	}
    	
    	
    	

    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",OddService.list(new QueryWrapper<Odd>().orderByDesc("odd")));
        map.put("count",a.size());
    	map.put("code",0);
        map.put("msg"," ");
    return map;
    }
    @RequestMapping("/printstatus")
    public String printstatus(Integer id){
    	Odd odd=OddService.getById(id);
    	odd.setPrintstatus(1);
    	OddService.updateById(odd);
    return "";
    }
    @RequestMapping("/seleprintstatus")
    public Object seleprintstatus(Integer id){ 
    	Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list(new QueryWrapper<Odd>().eq("printstatus", 0).eq("status", 1));
    	List<String> s=new ArrayList<String>();
    	List<String> href=new ArrayList<String>();
    	for (int i = 0; i < a.size(); i++) {
			s.add("单号:"+a.get(i).getOdd());
			href.add("syso.html?"+a.get(i).getOdd());
		}
        map.put("string",s);
        map.put("href",href);
        map.put("data",OddService.list());
        map.put("count",a.size());
    	map.put("code",0);
        map.put("msg"," ");
    return map;
    }
}
